//
//  NetworkTools.swift
//  swiftAFN网络工具封装
//Copyright © 2016年 zhangliming. All rights reserved.
//
//      一定要记得建立桥接文件并在buildingSetting中设置桥接文件路径！！！！
//

import UIKit

import AFNetworking

// 请求类型枚举

enum ZHRequestMethod:String {

    case GET = "GET"

    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {

    ///应用程序ID

    let appKey = "3369651578"

    ///应用程序秘钥

    let appSecret = "b36c92e00447c3a0de400c7ef203df69"

    /// 应用程序重定向地址
    let redirectURI = "http://baidu.com"

    /// 定义请求

    var authriszeRequest: NSURLRequest {

            let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURI)"

            let url = NSURL(string:urlString)

            return NSURLRequest(URL: url!)

        }

    //工具单例

    static let shardTools : NetworkTools = {

        let tools = NetworkTools()

        //设置反序列化格式

        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")

        //开启空值过滤

        (tools.responseSerializer as! AFJSONResponseSerializer).removesKeysWithNullValues = true

        return tools

    }()

    //封装方法

    func request(requestType:ZHRequestMethod, URLString: String, parameters: AnyObject?, finshed:(result:[String: AnyObject]?) -> ()) {

        ///成功回调

        let success = {(task: NSURLSessionDataTask, responseObject: AnyObject?) ->Void in

            if let result = responseObject as? [String:AnyObject]{

                finshed(result:result)

            }else{

                print("数据格式错误！")

                finshed(result: nil)

            }
        }
        ///失败回调

        let failure = {(task: NSURLSessionDataTask?, error: NSError) -> Void in

            print("网络请求失败：\(error)")

            finshed(result: nil)

        }

        if requestType == .GET {

            //GET请求

            GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)

        }

        if requestType == .POST {

            // POST请求

            POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)

        }
    }

    }

extension NetworkTools {


    //MARK:-加载accessToken请求

    func loadAccessToken (grant_type:String, code:String, finshed:([String:AnyObject]?) ->()) {

        ///请求地址

        let urlString = "https://api.weibo.com/oauth2/access_token"

        ///请求参数

        let parameters = ["client_id":appKey,
            "client_secret":appSecret,
            "grant_type":grant_type,
            "code":code,
            "redirect_uri":redirectURI]

        request(.POST, URLString: urlString, parameters: parameters) {result in

           // print(result)

            guard let result = result,

                uid = (result["uid"] as? String),

                access_token = (result["access_token"]as?String) else {

                    print("token格式错误！")
                    
                    return
            }

            ///获取用户信息
            
            NetworkTools.shardTools.loadUserInfo(uid, access_token: access_token){ userDict in

                guard var userdict = userDict else {

                    print("获取用户信息失败！")

                    return
                }
             ///给字典赋值

                for (k, v) in userdict {

                    userdict[k] = v

                }

                finshed(userdict)
            }
        }
    }
}
